package cn.onepiece.smili.render.util;

import java.io.*;

import javax.servlet.http.HttpServletResponse;

/**
 * @Author: haoting.wang
 * @Date: Created in 上午9:47 2017/5/31
 */
public class FileUtil {

    /**
     * 递归删除目录下的所有文件及子目录下所有文件
     *
     * @param dir 将要删除的文件目录
     * @return boolean Returns "true" if all deletions were successful. If a deletion fails, the method stops attempting
     * to delete and returns "false".
     */
    public static boolean deleteDir(File dir) {
        if (dir == null) {
            return false;
        }
        if (dir.isDirectory()) {
            String[] children = dir.list();
            for (int i = 0; i < children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }
        // 目录此时为空，可以删除
        return dir.delete();
    }

    public static boolean deleteDir(String dir) {
        File file = new File(dir);
        return deleteDir(file);
    }

    public static void downloadFile(File file, HttpServletResponse response) throws Exception {

        BufferedInputStream fis = null;
        OutputStream toClient = null;
        try {
            fis = new BufferedInputStream(new FileInputStream(file));
            // 以流的形式下载文件。
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            // 清空response
            response.reset();
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition",
                               "attachment;filename=" + new String(file.getName().getBytes("UTF-8"), "ISO-8859-1"));

            toClient = new BufferedOutputStream(response.getOutputStream());
            toClient.write(buffer);
            toClient.flush();
        } finally {
            if (fis != null) {
                fis.close();
            }
            if (toClient != null) {
                toClient.close();
            }
        }

    }
}
